package org.dy.upload;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.dy.util.BlobUtils;

public class UploadUtils {

	private List allowedExtensions;

	private List deniedExtensions;

	private String encoding;

	private int maxSize = 1024 * 1024;

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public int getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(int maxSize) {
		this.maxSize = maxSize;
	}

	public List getAllowedExtensions() {
		return allowedExtensions;
	}

	public void setAllowedExtensions(String allowedExtensions) {
		this.allowedExtensions = stringToArrayList(allowedExtensions);
	}

	public List getDeniedExtensions() {
		return deniedExtensions;
	}

	public void setDeniedExtensions(String deniedExtensions) {
		this.deniedExtensions = stringToArrayList(deniedExtensions);
	}

	@SuppressWarnings("deprecation")
	public MultipartFormBean getFileFromRequest(HttpServletRequest request) {
		try {
			if (encoding != null)
				request.setCharacterEncoding(encoding);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			MultipartFormBean resultBean = new MultipartFormBean();

			String encoding = request.getCharacterEncoding();

			DiskFileUpload upload = new DiskFileUpload();
			upload.setHeaderEncoding(encoding);
			upload.setFileSizeMax(maxSize);
			List items = upload.parseRequest(request);

			Map fields = new HashMap();

			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					fields.put(item.getFieldName(), item.getString(encoding));
				} else {
					String ext = getFileExt(item.getName());
					if(ext==null)
						continue;
					if (!extIsAllowed(ext)) {
						throw new FileUploadException("Upload file format '"
								+ ext + "' is not accepted!");
					}
					resultBean.addFileItem(item);
				}

			}
			resultBean.setFields(fields);

			return resultBean;
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	private String getFileExt(String fileName) {
		if (fileName == null||fileName.trim().equals(""))
			return null;
		else
			return fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	public void downloadFile(FormFileBean bean, HttpServletResponse response) {
		try {
			if (bean == null)
				return;

			if (encoding != null)
				response.setCharacterEncoding(encoding);
			else
				encoding = response.getCharacterEncoding();

			response.setContentType("application/x-msdownload");// oper save as
																// �Ի���
			response.setHeader("Content-Disposition", "attachment;"
					+ "filename=\""
					+ new String(bean.getFileName().getBytes(encoding),
							"ISO8859_1") + "\"");

			OutputStream os = response.getOutputStream();
			BlobUtils.saveBytes(os, bean.getBinary());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Helper function to convert the configuration string to an ArrayList.
	 */

	private ArrayList stringToArrayList(String str) {

		String[] strArr = str.split("\\|");

		ArrayList<String> tmp = new ArrayList<String>();
		if (str.length() > 0) {
			for (int i = 0; i < strArr.length; ++i) {
				// System.out.println(i + " - " + strArr[i]);
				tmp.add(strArr[i].toLowerCase());
			}
		}
		return tmp;
	}

	/**
	 * Helper function to verify if a file extension is allowed or not allowed.
	 */

	public boolean extIsAllowed(String ext) {

		ext = ext.toLowerCase();
		if (allowedExtensions == null || deniedExtensions == null)
			return true;
		if (allowedExtensions.contains(ext)) {
			if (!deniedExtensions.contains(ext))
				return true;
		}

		return false;
	}
}
